###############################
### Quick Thematic Map      ###
###############################
rm(list = ls())

# fix input string errors
Sys.setlocale('LC_ALL', 'C')
options(scipen=20)

##create folder structure
mainDir <- "" # insert your path

subDir <- "Replication_Files/Results/graphs/R_out"
if (file.exists(file.path(mainDir, subDir))){
  setwd(file.path(mainDir, subDir))
} else {
  dir.create(file.path(mainDir, subDir))
  setwd(file.path(mainDir, subDir))
}

# required
lop <- c("raster", "sp", "tmap","readstata13", "sf", "doBy","OpenStreetMap", "tmaptools")
newp <- lop[!(lop %in% installed.packages()[,"Package"])]
if(length(newp)) install.packages(newp)
lapply(lop, require, character.only = TRUE)


## zone data
grid.sf <- st_read("../../../Data/country_regions/gadm1_clean.shp")


## data
dta <- read.dta13("../../../Data/Merge/IDA_Aid_GED_ADM1.dta")


### get sf object for entire African countries
africa_countries <- st_read("../../../Data/country_regions/gadm28_adm0.shp")
africa_countries <- subset(africa_countries, UNREGION2=="Africa")
# manually set Reunion as Island
africa_countries[which((africa_countries$NAME_ENGLI=="Reunion")), which(names(africa_countries)=="Islands")] <- 1 
africa_countries <- subset(africa_countries, Islands==0)
#add Madagscar and Mauritius to sample despite being islands
isos <- c(as.character(unique(africa_countries$ISO)), "MDG", "MUS")
africa_countries$ISO <- as.character(africa_countries$ISO)

## Get sf data
gadm1_africa <- grid.sf %>% 
  subset(., ISO%in%isos) 
gadm1_africa$ISO <- as.character(gadm1_africa$ISO)

###############################
###       AID Data
###############################

## subset data for Africa
africa.df <- subset(dta, unregion2=="Africa" & transaction_year<=2012)
africa.df$conflict_years <- 0
africa.df$conflict_years[which(africa.df$brd_adm1>=5)] <- 1
### get summary statistics for regions
africa_max.df <- summaryBy(conflict_years~ID_adm1, data = africa.df, FUN = sum, keep.names = T, id=c("DAC_1995"))

## merge dta with sf
merge.sf <- merge(grid.sf, africa_max.df, by="ID_adm1")
#merge.sf$conflict_years[which(merge.sf$conflict_years==0)] <-NA

## filter out small islands
merge.sf <- merge.sf[merge.sf$ISO %in% isos,]
merge.sf$ISO <- as.character(merge.sf$ISO)

########IDA###########
## load raw aid data to plot as points
location <- read.csv("../../../Data/Aid/locations.csv")

transaction <- readxl::read_xlsx("../../../Data/Aid/IDA_IBRD_transactions.xlsx")

transaction$project_id <- transaction$projectid
transaction$projectid <- NULL
aid.df <- merge(location, transaction, by=c("project_id"))
### subset IDA data for Africa
aid.df <- subset(aid.df, financier=="IDA") 
aid.df <- subset(aid.df, grepl("Africa", aid.df$gazetteer_adm_name)==T)
aid.df<- subset(aid.df, grepl("Comoros", aid.df$gazetteer_adm_name)==F)
aid.df<- subset(aid.df, grepl("Mayotte", aid.df$gazetteer_adm_name)==F)
aid.df <- subset(aid.df, precision_code<=3)
aid.df[,"Donor"] <- "World Bank Aid" 

aid.sf <- st_as_sf(aid.df, coords = c("longitude", "latitude"))
# ## keep only geometry and donor information
# keep <- c("geometry", "Donor")
# aid.sf <- aid.sf[,names(aid.sf) %in% keep]
########China Aid##########
aid_china.df <- read.csv("../../../Data/Aid/spatial_join_adm1_chinese_aid.csv", dec = ",", stringsAsFactors=F)

### subset IDA data for Africa
aid_china.df <- subset(aid_china.df, flow_class.C.254=="ODA-like") 
aid_china.df <- subset(aid_china.df, precision_.N.10.0<=3)
aid_china.df <- aid_china.df[aid_china.df$ISO.C.3 %in% isos,]
aid_china.df[,"Donor"] <- "Chinese Aid" 

aid_china.sf <- st_as_sf(aid_china.df, coords = c("longitude.N.19.11", "latitude.N.19.11"))
# ## keep only geometry and donor information
# keep <- c("geometry", "Donor")
# aid_china.sf <- aid_china.sf[,names(aid_china.sf) %in% keep]
# ## create dataset containing information of WB and China
# aid_all.sf <- rbind(aid.sf, aid_china.sf)
# aid_all.sf <- cbind(aid_china.sf)


## set up font family
# install.packages("extrafont")
library(extrafont)
# font_import()
# y
loadfonts()
loadfonts(device="win")

## Create PDF and png
plot_conf_ida <- function(maplayout="esri-topo"){
  ## load basemap data
  # read OSM raster data
  osm_afri <- read_osm(africa_countries, ext=1.1, type=maplayout)
  print (
    tm_shape(osm_afri) +
      tm_rgb() +
    tm_shape(africa_countries)+
      tm_borders(lwd = 2)+
    tm_shape(gadm1_africa) +
      tm_borders(col = "grey40", alpha = 0.4) +
    tm_shape(aid.sf) +
      tm_dots(col="#3A55A4"
              , shape = 20
              , scale=4.5
              , border.lwd = 1) +
    tm_shape(aid_china.sf) +
      tm_dots(col="#D4529A"
              , shape = 23
              , scale=4.5
              , border.col="black"
              , border.lwd = 1) +
      # add legend manually
    tm_add_legend(type = "symbol"
                  , shape = c(20,23)
                  , size = c(2,1)
                  , col = c("#3A55A4", "#D4529A")
                  , title ="Aid Projects"
                  , labels = c("World Bank Aid", "Chinese Aid"))+
    tm_scale_bar(size =1
                 , width = 0.2)+
    tm_layout(legend.position = c("left", "bottom")
                , legend.text.size = 1.4
                , legend.title.size = 2.2
                , fontfamily = "Helvetica"
                , frame = F #put frame around graph?
                , legend.outside = F # legend outside of margin?
                , outer.margins = c(0, 0, 0, 0) # Relative margins between device and frame (bottom, left, top, right)
      )
  )
}



## png format
png(paste0("map_aid_only.png"))
plot_conf_ida(maplayout="nps")
dev.off()

## esp format
# setEPS()
# postscript("map_aid_only.eps")
# plot_conf_ida()
# dev.off()

## pdf format
# pdf(paste0("map_aid_only.pdf"), width=8, height=8)
# par(mfrow=c(1,1))
# par(mar = c(0,0,0,0)) # c(bottom, left, top, right)
# plot_conf_ida(maplayout="nps")
# dev.off()


